<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="layui/css/layui.css">
    <title>Test</title>
</head>
<body>
        <ul class="layui-nav">
            <li class="layui-nav-item layui-col-md-offset8">
                <a href="">奖品细节设置</span></a>
            </li>
            <li class="layui-nav-item layui-this">
                <a href="">人员设置</span></a>
            </li>
            <li class="layui-nav-item">
                <a href="">个人中心<span class="layui-badge-dot"></span></a>
            </li>
            <li class="layui-nav-item">
                <a href=""><img src="https://t.cn/RCzsdCq" class="layui-nav-img">我</a>
                <dl class="layui-nav-child">
                <dd><a href="javascript:;">修改信息</a></dd>
                <dd><a href="javascript:;">安全管理</a></dd>
                <dd><a href="javascript:;">注销</a></dd>
                </dl>
            </li>
        </ul>
        
        <div>
            <div id="select-head-div" style="padding: 5px 20px;border: 1px #1e1616;width: 400px;height: 300px;margin: 133px auto auto;display: block;box-shadow: 0px 1px 4px 2px #c2c2c2; display: none;">
                <form class="layui-form layui-form-pane">
                    <h2>请输入要显示的列</h2>
                    <hr class="layui-bg-green">
                    <div>
                        <div id="head-show-div" style="height: 182px;">
                            <input type="checkbox" title="1" name="0">
                            <input type="checkbox" title="1" name="1">
                            <input type="checkbox" title="1" name="2">
                            <input type="checkbox" title="1" name="3">
                            <input type="checkbox" title="1" name="4">
                            <input type="checkbox" title="1" name="5">
                            <input type="checkbox" title="1" name="6">
                            <input type="checkbox" title="1" name="7">
                            <input type="checkbox" title="1" name="8">
                            <input type="checkbox" title="1" name="9">
                        </div>
                    </div>
                </form>
                <div style="text-align: center;">

                    <button id="select-head-but" class="layui-btn layui-btn-radius" style="width: 90px;margin-right: 40px;">确定</button>
                    <button id="cancel-head-but" class="layui-btn layui-btn-radius layui-btn-primary" style="width: 90px;">取消</button>
                </div>
            </div>
            <div id="upload-file-div" class="layui-col-md6 layui-col-md-offset3 fade-out" style="margin-top: 19%;">
                    <button type="button" class="layui-btn layui-btn-radius layui-btn-fluid fade-out" id="upload_xls">
                        <i class="layui-icon">&#xe67c;</i>上传名单表格
                    </button>
            </div>
            
            <input type="file" id="btn_file" style="display:none">
            <div id="form_display" style="padding: 75px;">
                
            </div>
        </div>

<script src="js/jquery.js"></script>
<script src="layui/layui.js"></script>
<script type="text/javascript" src="js/xlsx.core.min.js"></script>
<script>

var MEMBER_FORM = {
    headers: null,
    members: null,
}


$(function(){
    var HEAD;
    var MEMBER;

    $('#upload_xls')[0].onclick = function(){
        $('#btn_file').click();
    };

    $('#btn_file')[0].onchange = function(){
        var file = $('#btn_file')[0].files[0];
        if (file.name.endsWith('.xlsx')) {
            readWorkbookFromLocalFile(file, form2Table);
        } else {
            layer.alert('请传入表格文件!', {icon: 2});
        }
    };

    $('#select-head-but').click(function(){
        var selectIdx = [];
        $('#select-head-div > form input').each((idx, e) => {
            selectIdx.push(e.checked);
        });
        console.log(selectIdx);
        

        if (selectIdx.indexOf(true) >= 0) {
            $('#select-head-div').remove();
            $('#upload-file-div').remove();
            renderTable(selectIdx);
        } else {
            layer.alert('请至少选择一个显示项!', {icon: 2});
        }
    });

    $('#cancel-head-but').click(function(){
        $('#select-head-div').hide();
        $('#upload-file-div').show();
        var file = $('#btn_file');
        file.after(file.clone().val(""));
        file.remove();

        //重新注册
        $('#btn_file')[0].onchange = function(){
            var file = $('#btn_file')[0].files[0];
            if (file.name.endsWith('.xlsx')) {
                readWorkbookFromLocalFile(file, form2Table);
            } else {
                layer.alert('请传入表格文件!', {icon: 2});
            }
        };
    });

    //一般直接写在一个js文件中
    layui.use(['layer', 'form', 'element'], function(){
        var layer = layui.layer
        ,form = layui.form
        ,element = layui.element;
    });

    function readWorkbookFromLocalFile(file, callback) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary'});
            if(callback) callback(workbook);
        };
        reader.readAsBinaryString(file);
    }

    function form2Table(workbook) {
        var sheetNames = workbook.SheetNames; // 工作表名称集合
        var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
        // renderTable(XLSX.utils.sheet_to_csv(worksheet));
        popUpHeadSelector(XLSX.utils.sheet_to_csv(worksheet));
    }

    function popUpHeadSelector(csv) {
        var rows = csv.split('\n');
        rows.pop();
        rows = rows.map(row => row.split(','));
        var headers = rows.shift();
        HEAD = headers;
        MEMBER = rows;
        $(`#head-show-div > div:gt(${HEAD.length - 1})`).remove();
        $(`#head-show-div > input:gt(${HEAD.length - 1})`).remove();
        
        headers.map((e, idx) => $(`#head-show-div span:eq(${idx})`).text(e));

        $('#upload-file-div').hide();
        setTimeout(() => {
            $('#select-head-div').addClass('layui-anim layui-anim-scale');
            $('#select-head-div').show();
        }, 300);
    }

    function renderTable(selectIdx) {

        //清洗
        HEAD = HEAD.filter((e, idx) => selectIdx[idx]);
        MEMBER = MEMBER.map(row => row.filter((e, idx) => selectIdx[idx]));
        MEMBER_FORM.headers = HEAD;
        
        rows = MEMBER.map(MEMBER => {
            var c = MEMBER.map(col => `<td><input type="text" class="layui-input" value="${col}"></td>`)
            return c.join() + '<td><button class="layui-btn del_tr"><i class="layui-icon" style="font-size: 35px;text-align: center;">ဇ</i></button></td></tr>';
        })
        
        
        $('#form_display').html(`
            <div class="layui-anim layui-anim-up">
                <form action="#" id="form_form">
                    <div class="layui-row">
                        <div class="layui-col-md11">
                            <button class="layui-btn layui-btn-fluid" id="upload_form" style="width: 99%;">保存名单</button>
                        </div>
                        <div class="layui-col-md1" style="width: 6%; left: 14px;">
                            <button class="layui-btn layui-btn-fluid layui-btn-warm" id="add_member"><i class="layui-icon layui-icon-add-1" style="font-size: 35px;text-align: center;"></i></button>
                        </div>
                    </div>
                    <table class="layui-table" id="form_table">
                        <colgroup>
                            ${'<col>'.repeat(HEAD.length)}
                            <col width="11">
                        </colgroup>
                        <thead>
                            <tr>
                                ${HEAD.map(head => `
                                    <th>${head}</th>
                                `)}
                                <th>删除</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                ${rows}
                            </tr>
                        </tbody>
                    </table>
                </form>
            </div>
        `.replace(/,/g, ""));
        // 出现很多逗号...不知道为什么

        $('#add_member').click(function(){
            $('#form_table tbody').prepend(`
                <tr>
                    ${'<td><input type="text" class="layui-input"></td>'.repeat(MEMBER_FORM.headers.length)}
                    <td><button class="layui-btn del_tr"><i class="layui-icon" style="font-size: 35px;text-align: center;">ဇ</i></button></td></tr>
                </tr>
            `);
            
            // 重新注册
            $('.del_tr').click(function(){
                $(this).parents('tr').remove();
            });

            $('#form_form input').blur(function(){
                $(this).val().trim() === "" ? $(this).css('border', '1.3px solid red') : $(this).css('border', '1px solid #e6e6e6');
            });
        });

        $('.del_tr').click(function(){
            $(this).parents('tr').remove();
        });

        $('#form_form input').blur(function(){
            $(this).val().trim() === "" ? $(this).css('border', '1.3px solid red') : $(this).css('border', '1px solid #e6e6e6');
        });

        $('#upload_form').click(function() {
            var parts = $('#form_form input').length / MEMBER_FORM.headers.length;
            parts = Array.apply(null, Array(parts)).map((e, idx) => idx);

            //load and check
            var hasEmpety = false;
            var memberList = parts.map((part) => {
                let startIdx = part * MEMBER_FORM.headers.length;
                var handlerList = $('#form_form input').slice(startIdx, startIdx + MEMBER_FORM.headers.length);
                return handlerList.map((idx, ele) => {
                    if (ele.value === "") {
                        $(ele).css('border', '1.3px solid red');
                        hasEmpety = true;
                    }
                    return ele.value;
                });
            });

            if (hasEmpety) {
                layer.alert('请完整输入!', {icon: 2});
            } else {
                MEMBER_FORM.members = memberList;

                localStorage.setItem('MEMBER_FORM', JSON.stringify(MEMBER_FORM));
                
                layer.alert('保存成功', {icon: 1});
            }
        });
    };
});
</script>
</body>
</html>

